package com.bdqn.dom;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class Phone6 {
    public static void main(String[] args) {
        //工厂实例
        DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
        //解析器
        DocumentBuilder db = null;
        try {
            db = dbf.newDocumentBuilder();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        }
        //doc
        Document doc = null;
        try {
            doc = db.parse("src/xml/Phone.xml");
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        //找到要删除的节点
        NodeList list=doc.getElementsByTagName("Brand");
        for (int i=0;i<list.getLength();i++){
            Element brandElement=(Element)list.item(i);
            String brandName=brandElement.getAttribute("name");
            if (brandName.equals("SAMSUNG")){
                brandElement.getParentNode().removeChild(brandElement);
            }
        }

        //省略保存XML文件的代码
        TransformerFactory transformerFactory=TransformerFactory.newInstance();
        Transformer transformer = null;
        try {
            transformer = transformerFactory.newTransformer();
        } catch (TransformerConfigurationException e) {
            e.printStackTrace();
        }
        DOMSource domSource=new DOMSource(doc);
        //设置编码类型
        transformer.setOutputProperty(OutputKeys.ENCODING,"gb2312");
        StreamResult  result = null;
        try {
            result = new StreamResult(new FileOutputStream("src/xml/Phone.xml"));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        //吧DOM树转换为XML文件
        try {
            transformer.transform(domSource,result);
        } catch (TransformerException e) {
            e.printStackTrace();
        }
    }
}
